﻿//用于保存上传对象
var swf_uploader = null;

//上传窗体
var win_upload = null;

//用于记录是否安装Flash
var flash_enabled = null;

//检查Flash控件是否安装
function detectFlash()
{
    try
    {
        if (navigator.mimeTypes.length > 0)
        {
            //尝试创建
            return navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin != null;
        }
        else if (window.ActiveXObject)
        {
            //尝试创建对象
            new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
            //返回已经安装
            return true;
        }
        else
        {
            //无法检查，则返回已经安装
            return true;
        }
    }
    catch (e)
    {
        return false;
    }
}

//Flash控件加载完毕
function flashReady()
{
    try
    {
        //设置参数
        if (win_upload.options)
        {
            //设置文件尺寸限制
            if (win_upload.options.file_size_limit)
            {
                swf_uploader.setFileSizeLimit(win_upload.options.file_size_limit);
            }

            //设置文件类型
            if (win_upload.options.file_types)
            {
                swf_uploader.setFileTypes(win_upload.options.file_types, win_upload.options.file_types_description);
            }
        }
    }
    catch (e)
    {
        alert(e);
    }
}

//文件被加入队列
function fileQueued(file)
{
    //设置标题
    var txtFileName = win_upload.down('#txtFileName');
    var txtDisplayName = win_upload.down('#txtDisplayName');

    //获得文件名称
    var fileName = file.name;

    //判断是否为全路径
    var index = fileName.lastIndexOf('\\');

    //如果是全路径，则只取文件名部分
    if (index != -1)
    {
        fileName = fileName.substr(index + 1, fileName.length - index - 1);
    }

    //设置文件名称
    txtFileName.setValue(fileName);
    txtDisplayName.setValue(fileName);
}

//文件加入队列错误
function fileQueueError(file, errorCode, message)
{
    try
    {
        //根据不同的错误代码做不同的处理
        switch (errorCode)
        {
            case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                //提示错误信息
                Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: '错误码：' + errorCode + ' (上传队列超过允许的长度) <br/>文件名称：' + file.name + " <br/>错误信息：" + message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
                break;
            case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                //提示错误信息
                Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: '错误码：' + errorCode + '(上传文件大小超过阈值) <br/>文件名称：' + file.name + " <br/>错误信息：" + message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
                break;
            case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                //提示错误信息
                Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: '错误码：' + errorCode + '(IO错误) <br/>文件名称：' + file.name + " <br/>错误信息：" + message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
                break;
            case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                //提示错误信息
                Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: '错误码：' + errorCode + '(IO错误) <br/>文件名称：' + file.name + " <br/>错误信息：" + message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
                break;
            default:
                //提示错误信息
                Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: '错误码：' + errorCode + '(未知错误) <br/>文件名称：' + file.name + " <br/>错误信息：" + message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
                break;
        }
    }
    catch (ex)
    {
        //提示错误信息
        Ext.MessageBox.show
        (
            {
                title: Common.ApplicationName,
                msg: ex,
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            }
        );
    }
}

//打开文件对话框
function fileDialogStart()
{
}

//文件对话框关闭
function fileDialogComplete(numFilesSelected, numFilesQueued)
{
    //停止上传
    swf_uploader.stopUpload();
}

//开始上传
function uploadStart(file)
{
}

//上传进度
function uploadProgress(file, bytesLoaded, bytesTotal)
{
}

//上传成功
function uploadSuccess(file, serverData)
{
    //用于保存反馈对象
    var responseData = {};

    //解析反馈对象
    try
    {
        //解析反馈数据
        responseData = Ext.JSON.decode(serverData, false);
    }
    catch (e)
    {
        //提示错误信息
        Ext.MessageBox.show
        (
            {
                title: Common.ApplicationName,
                msg: '无法解析文件上传反馈。<br/>' + e,
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            }
        );
    }

    //判定是否上传成功
    if (responseData.success)
    {
        //回调
        if (win_upload.options && win_upload.options.callback)
        {
            //执行回调
            win_upload.options.callback(responseData, win_upload.options);
        }
    }
    else
    {
        //判定是否没有登录
        if (responseData.code == ErrorCode.Unauthenticated)
        {
            //提示错误信息
            Ext.MessageBox.show
            (
                {
                    title: Common.ApplicationName,
                    msg: responseData.message,
                    buttons: Ext.Msg.OK,
                    icon: Ext.Msg.INFO
                }
            );

            //跳转到首页
            window.location = "/";
        }
        //判定是否没有授权
        else if (responseData.code == ErrorCode.Unauthorized)
        {
            //提示错误信息
            Ext.MessageBox.show
            (
                {
                    title: Common.ApplicationName,
                    msg: responseData.message,
                    buttons: Ext.Msg.OK,
                    icon: Ext.Msg.ERROR
                }
            );
        }
        else
        {
            //提示错误信息
            Ext.MessageBox.show
            (
                {
                    title: Common.ApplicationName,
                    msg: responseData.message,
                    buttons: Ext.Msg.OK,
                    icon: Ext.Msg.ERROR
                }
            );
        }
    }
}

//上传失败
function uploadError(file, errorCode, message)
{
    try
    {
        //根据不同的错误代码做不同的处理
        switch (errorCode)
        {
            case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
                //提示错误信息
                Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: '错误码：' + errorCode + '(HTTP) <br/>文件名称：' + file.name + " <br/>错误信息：" + message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
                break;
            case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
                //提示错误信息
                Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: '错误码：' + errorCode + '(上传失败) <br/>文件名称：' + file.name + " <br/>错误信息：" + message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
                break;
            case SWFUpload.UPLOAD_ERROR.IO_ERROR:
                //提示错误信息
                Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: '错误码：' + errorCode + '(IO错误) <br/>文件名称：' + file.name + " <br/>错误信息：" + message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
                break;
            case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
                //提示错误信息
                Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: '错误码：' + errorCode + '(安全性错误) <br/>文件名称：' + file.name + " <br/>错误信息：" + message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
                break;
            case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
                //提示错误信息
                Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: '错误码：' + errorCode + '(上传文件大小超过阈值) <br/>文件名称：' + file.name + " <br/>错误信息：" + message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
                break;
            case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
                //提示错误信息
                Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: '错误码：' + errorCode + '(验证失败) <br/>文件名称：' + file.name + " <br/>错误信息：" + message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
                break;
            case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
                //提示错误信息
                Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: '错误码：' + errorCode + '(取消上传) <br/>文件名称：' + file.name + " <br/>错误信息：" + message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
                break;
            case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
                //提示错误信息
                Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: '错误码：' + errorCode + '(停止上传) <br/>文件名称：' + file.name + " <br/>错误信息：" + message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
                break;
            default:
                //提示错误信息
                Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: '错误码：' + errorCode + '(未知错误) <br/>文件名称：' + file.name + " <br/>错误信息： " + message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
                break;
        }
    }
    catch (ex)
    {
        //提示错误信息
        Ext.MessageBox.show
                (
                    {
                        title: Common.ApplicationName,
                        msg: ex,
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    }
                );
    }
}

//上传完毕
function uploadComplete(file)
{
    try
    {
        //获得表单
        var form = win_upload.down('form');

        //重置数据
        form.getForm().reset();

        //启用按钮
        form.down('#btnOK').enable(true);
        form.down('#btnCancel').enable(true);

        //隐藏窗体
        win_upload.hide();
    }
    catch (e)
    {
        alert(e);
    }
}

//对象执行完毕
function queueComplete(numFilesUploaded)
{
}

//上传文件
function UploadFile(options)
{
    //检查Flash插件的安装情况
    if (flash_enabled == null)
    {
        flash_enabled = detectFlash();
    }

    //判定Flash插件是否安装
    if (!flash_enabled)
    {
        //提示信息
        Ext.MessageBox.show
        (
            {
                title: Common.ApplicationName,
                msg: '文件上传需要使用Flash插件，当前浏览器中尚未安装Flash插件,请安装Flash插件之后，再执行文件上传操作。<br/><br/>点击“确定”之后开始安装Flash插件。',
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.INFO,
                fn: function (button)
                {
                    //打开Flash的安装地址
                    window.open('http://www.adobe.com/go/getflashplayer');
                }
            }
        );

        //直接返回
        return;
    }

    //判定窗体是否创建
    if (!win_upload)
    {
        //创建窗体
        win_upload = new Ext.Window
        (
            {
                title: '上传附件',
                maximizable: false,
                maximized: false,
                width: 480,
                height: 240,
                bodyBorder: false,
                draggable: true,
                isTopContainer: true,
                modal: true,
                resizable: false,
                bodyPadding: 0,
                closeAction: 'hide',
                closable: false,
                layout: 'fit',
                fieldDefaults:
                {
                    labelAlign: 'left',
                    labelWidth: 72,
                    anchor: '100%'
                },
                listeners:
                {
                    hide: function (window, options)
                    {
                        //获得表单对象
                        var form = window.down('form');

                        //判定是否存在
                        if (form)
                        {
                            //显示进度条
                            form.setLoading(false);
                        }
                    },
                    show: function ()
                    {
                        try
                        {
                            //判定上传控件是否已经创建
                            if (!swf_uploader)
                            {
                                //创建设置
                                var settings =
                                {
                                    flash_url: upload_flash_url,
                                    upload_url: '',
                                    file_size_limit: 0,
                                    file_types: '*.*',
                                    file_types_description: 'All Files',
                                    file_upload_limit: "0",
                                    file_queue_limit: "0",
                                    debug: false,

                                    //按钮设置
                                    button_image_url: upload_button_url,
                                    button_width: "66",
                                    button_height: "22",
                                    button_placeholder_id: "btnSelectFile",
                                    button_text: '浏览文件',
                                    button_text_left_padding: 6,
                                    button_text_top_padding: 0,

                                    //处理事件
                                    swfupload_loaded_handler: flashReady,
                                    file_dialog_start_handler: fileDialogStart,
                                    file_dialog_complete_handler: fileDialogComplete,
                                    file_queued_handler: fileQueued,
                                    file_queue_error_handler: fileQueueError,
                                    upload_start_handler: uploadStart,
                                    upload_progress_handler: uploadProgress,
                                    upload_error_handler: uploadError,
                                    upload_success_handler: uploadSuccess,
                                    upload_complete_handler: uploadComplete,
                                    queue_complete_handler: queueComplete
                                };

                                //创建上传控件
                                swf_uploader = new SWFUpload(settings);
                            }

                            //判断是否有设置信息
                            if (options)
                            {
                                //设置标题
                                if (options.title)
                                {
                                    win_upload.setTitle(options.title);
                                }

                                //获得表单
                                var form = this.down('form');

                                //启用按钮
                                form.down('#btnOK').enable(true);
                                form.down('#btnCancel').enable(true);

                                //获得文件名输入框
                                var txtFileName = form.down('#txtFileName');

                                //判断模式
                                if (options.mode == 0)
                                {
                                    //设置标题
                                    txtFileName.labelEl.update('日志照片');
                                    txtFileName.emptyText = options.file_size_limit_tip;
                                    txtFileName.setRawValue(txtFileName.emptyText);
                                    form.down('#txtDisplayName').labelEl.update('照片名称');
                                    form.down('#chkIsOpen').hide();
                                    form.down('#txtMemo').show();
                                }
                                else if (options.mode == 1)
                                {
                                    //设置标题
                                    txtFileName.labelEl.update('工程附件');
                                    txtFileName.emptyText = options.file_size_limit_tip;
                                    txtFileName.setRawValue(txtFileName.emptyText);
                                    form.down('#txtDisplayName').labelEl.update('附件名称');
                                    form.down('#chkIsOpen').show();
                                    form.down('#txtMemo').hide();
                                }
                                else if (options.mode == 2)
                                {
                                    //设置标题
                                    txtFileName.labelEl.update('事件附件');
                                    txtFileName.emptyText = options.file_size_limit_tip;
                                    txtFileName.setRawValue(txtFileName.emptyText);
                                    form.down('#txtDisplayName').labelEl.update('附件名称');
                                    form.down('#chkIsOpen').hide();
                                    form.down('#txtMemo').hide();
                                }
                            }
                        }
                        catch (e)
                        {
                            alert(e);
                        }
                    }
                },
                items:
                [
                    {
                        xtype: 'form',
                        method: 'POST',
                        waitMsgTarget: true,
                        standardSubmit: false,
                        fileUpload: true,
                        waitTitle: Common.ApplicationName,
                        frame: false,
                        bodyPadding: 12,
                        bodyStyle: 'background-color:White;margin:0;',
                        bodyBorder: false,
                        border: 0,
                        autoScroll: true,
                        defaultType: 'textfield',
                        autoScroll: false,
                        fieldDefaults:
                        {
                            labelAlign: 'left',
                            labelWidth: 72,
                            anchor: '100%',
                            msgTarget: 'qtip',
                            autoFitErrors: true,
                            disabledCls: ''
                        },
                        items:
                        [
                            {
                                xtype: 'panel',
                                layout: 'column',
                                border: 0,
                                items:
                                [
                                    {
                                        xtype: 'textfield',
                                        fieldLabel: '项目附件',
                                        name: 'FileName',
                                        itemId: 'txtFileName',
                                        allowBlank: false,
                                        readOnly: true,
                                        width: 370
                                    },
                                    {
                                        xtype: 'displayfield',
                                        value: '',
                                        width: 8
                                    },
                                    {
                                        xtype: 'panel',
                                        border: 0,
                                        height: 22,
                                        width: 66,
                                        contentEl: 'swf_upload'
                                    }
                                ]
                            },
                            {
                                xtype: 'textfield',
                                name: 'DisplayName',
                                itemId: 'txtDisplayName',
                                fieldLabel: '附件名称',
                                emptyText: '80个字符',
                                allowBlank: false,
                                maxLength: 80
                            },
                            {
                                xtype: 'checkbox',
                                itemId: 'chkIsOpen',
                                name: 'IsOpen',
                                fieldLabel: '公共附件',
                                inputValue: 'true',
                                value: 'true'
                            },
                            {
                                xtype: 'textareafield',
                                itemId: 'txtMemo',
                                name: 'Memo',
                                fieldLabel: '照片说明',
                                emptyText: '照片说明信息（最长200个字符）',
                                maxLength: 200,
                                autoScroll: true
                            }
                        ],
                        buttons:
                        [
                            {
                                text: '确定',
                                height: 26,
                                margin: 3,
                                itemId: 'btnOK',
                                handler: function ()
                                {
                                    //设置上传路径
                                    swf_uploader.setUploadURL(options.url);

                                    //获得表单对象
                                    var form = win_upload.down('form');

                                    //获得上传参数
                                    var postParams =
                                    {
                                        ASPSESSID: session_id,
                                        AUTHID: auth_id,
                                        DisplayName: form.down('#txtDisplayName').getValue(),
                                        IsOpen: form.down('#chkIsOpen').getValue(),
                                        Memo: form.down('#txtMemo').getValue(),
                                        OwnerID: win_upload.options.OwnerID,
                                        FileType: win_upload.options.FileType
                                    };

                                    //设置上传参数
                                    swf_uploader.setPostParams(postParams);

                                    //执行上传
                                    swf_uploader.startUpload();

                                    //显示进度条
                                    form.setLoading({ msg: '正在上传文件，请稍候......' });

                                    //禁用按钮
                                    form.down('#btnOK').disable(true);
                                    form.down('#btnCancel').disable(true);
                                }
                            },
                            {
                                text: '取消',
                                height: 26,
                                margin: 3,
                                itemId: 'btnCancel',
                                handler: function ()
                                {
                                    //获得表单对象
                                    var form = this.up('form').getForm();
                                    //重置数据
                                    form.reset();
                                    //隐藏窗体
                                    this.up('window').hide();
                                }
                            }
                         ]
                    }
                ]
            }
        );
    }

    //设置变量
    win_upload.options = options;

    //显示窗体
    win_upload.show();
}